<!-- eslint-disable vue/no-reserved-component-names -->
<template>
  <div class="main">
    <!-- 左侧菜单 -->
    <el-aside class="sidebar" :class="{ 'sidebar-expanded': !isCollapse }">
      <el-menu default-active="3" class="el-menu-vertical-demo" :collapse="isCollapse" @open="handleOpen"
        @close="handleClose">
        <img id="logo" src="@/assets/logo.png" alt="智柜" @click="$router.push({ name: 'Index' })">
        <el-sub-menu index="1">
          <template #title>
            <el-icon>
              <Menu />
            </el-icon>
            <span>我的业务</span>
          </template>
          <el-menu-item-group title="订单记录">
            <el-menu-item index="1-1" @click="goToBusiness(1)">充值订单</el-menu-item>
            <el-menu-item index="1-2" @click="goToBusiness(2)">存取订单</el-menu-item>
          </el-menu-item-group>
<!--           <el-menu-item-group title="取件记录">
            <el-menu-item index="1-3" @click="goToBusiness(3)">待取快件</el-menu-item>
            <el-menu-item index="1-4" @click="goToBusiness(4)">已取快件</el-menu-item>
          </el-menu-item-group> -->
        </el-sub-menu>
        <el-menu-item index="2" @click="this.$router.push('/info/wallet')">
          <el-icon>
            <Wallet />
          </el-icon>
          <template #title>我的钱包</template>
        </el-menu-item>
        <el-menu-item index="3" @click="this.$router.push('/info/userinfo')">
          <el-icon>
            <User />
          </el-icon>
          <template #title>个人信息</template>
        </el-menu-item>
        <el-menu-item index="4" @click="this.$router.push('/info/interMsg')">
          <el-icon>
            <Message />
          </el-icon>
          <template #title>站内信</template>
        </el-menu-item>
        <el-menu-item index="5" @click="this.$router.push('/info/settings')">
          <el-icon>
            <Setting />
          </el-icon>
          <template #title>系统通知</template>
        </el-menu-item>
        <!-- 用户头像 -->
        <div class="layout" @click="layout1">
          <img :src="avatarUrl" style="height: 50px; border-radius: 50%; -webkit-user-drag: none;">
          <span v-if="!isCollapse" class="logout" @click="logout">退出登录</span>
        </div>
      </el-menu>
    </el-aside>

    <!-- 右侧内容 -->
    <div class="main-content">
      <el-container>
        <el-header class="header">
          <span class="left">
            <span style="margin-left: 100px; margin-right: 60px;">
              <WeatherDisplay></WeatherDisplay>
            </span>
            <span style="display: flex; align-items: end;">
              <p style="font-size: 26px; font-weight: 600;">个人中心✨</p>
              <p style="font-size: 16px; color: #91929b; margin-left: 10px;">
                欢迎回来~{{ currentUser }}🎊！
              </p>
            </span>
          </span>
          <span class="right">
            <!-- 使用 el-autocomplete 替换 input -->
            <el-autocomplete
              v-model="searchQuery"
              :fetch-suggestions="querySearch"
              placeholder="请输入要搜索的功能"
              class="search"
              @select="handleSelect"
              :trigger-on-focus="true"
              clearable
            >
              <template #default="{ item }">
                <span>{{ item.label }}</span>
              </template>
            </el-autocomplete>
            <span @mouseenter="showMsgCard = true" @mouseleave="showMsgCard = false">
              <span class="bell">
                <el-icon>
                  <Bell />
                </el-icon>
              </span>
              <transition name="fade">
                <div v-if="showMsgCard" class="msg">
                  <MsgBox :msgData="msgData" />
                </div>
              </transition>
            </span>
            <!-- 折叠/展开按钮 -->
            <span class="toggle-button" @click="toggleCollapse" :aria-expanded="!isCollapse">
              <svg viewBox="0 0 130 100" class="hamburger-icon">
                <rect class="bar1" x="10" y="20" width="120" height="12" rx="5" stroke="#425aef" fill="#425aef" />
                <rect class="bar2" x="10" y="50" width="120" height="12" rx="5" stroke="#425aef" fill="#425aef" />
                <rect class="bar3" x="10" y="80" width="120" height="12" rx="5" stroke="#425aef" fill="#425aef" />
              </svg>
            </span>
          </span>
        </el-header>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
import MsgBox from '@/components/MsgBox'
import { layout } from '@/utils/layout'
import axiosService from '@/utils/request'
import { showMsg } from '@/utils/showMsg'
import WeatherDisplay from '@/components/WeatherDisplay'
import {
  User,
  Wallet,
  Menu,
  Setting,
  Message,
  Bell
} from '@element-plus/icons-vue'

export default {
  components: {
    User,
    Wallet,
    // eslint-disable-next-line vue/no-reserved-component-names
    Menu,
    Message,
    Setting,
    MsgBox,
    WeatherDisplay,
    Bell
  },
  created()
  {
    this.avatarUrl = this.$store.state.user?.avatar
    this.currentUser = this.$store.state.user?.nickname
    this.init()
    this.initRouteMap()
  },
  data()
  {
    return {
      showMsgCard: false,
      isCollapse: true, // 控制菜单是否折叠
      msgData: [],
      searchQuery: '', // 搜索输入值
      routeMap: [], // 路由映射列表
      routeDisplayNames: {
        Index: '首页',
        gonggao: '公告',
        Services: '存取业务',
        About: '关于',
        Login: '登录',
        Info: '个人中心',
        myOrderpays: '充值订单',
        myOrdercqs: '存取订单',
        interMsg: '站内信',
        wallet: '我的钱包',
        userinfo: '个人信息',
        settings: '系统设置',
        admin: '管理员面板',
        adminindex: '管理员首页',
        userman: '用户管理',
        adminmsg: '消息管理',
        orderman: '订单管理',
        adminsys: '系统设置',
        statistics: '统计',
        Pay: '支付',
        GuiJiMap: '柜机地图',
        Loading: '加载页面'
      }
    }
  },
  methods: {
    init()
    {
      axiosService.get('/node/articles')
        .then(res =>
        {
          this.msgData = res.msg
        })
        .catch(e =>
        {
          showMsg('消息获取失败', e, 'error')
        })
    },
    goToBusiness(type)
    {
      switch (type)
      {
      case 1: this.$router.push('/info/myOrderpays'); break
      case 2: this.$router.push('/info/myOrdercqs'); break
      default:
        break
      }
    },
    toggleCollapse()
    {
      this.isCollapse = !this.isCollapse // 切换 isCollapse 的值
    },
    layout1()
    {
      layout(this)
    },
    // 初始化路由映射
    initRouteMap()
    {
      const routes = [
        {
          path: '/',
          name: 'Index',
          component: () => import('../views/Index.vue')
        },
        {
          path: '/gonggao',
          name: 'gonggao',
          component: () => import('../views/GongGao.vue')
        },
        {
          path: '/services',
          name: 'Services',
          component: () => import('../views/Services.vue')
        },
        {
          path: '/about',
          name: 'About',
          component: () => import('../views/About.vue')
        },
        {
          path: '/login',
          name: 'Login',
          component: () => import('../views/Login.vue')
        },
        {
          path: '/info',
          name: 'Info',
          component: () => import('../views/UserInfo.vue'),
          children: [
            {
              path: 'myOrderpays',
              component: () => import('../views/UserInfo/OrderPayment.vue')
            },
            {
              path: 'myOrdercqs',
              component: () => import('../views/UserInfo/OrderCqs.vue')
            },
            {
              path: 'interMsg',
              component: () => import('../views/UserInfo/InternalMsg.vue')
            },
            {
              path: 'wallet',
              component: () => import('../views/UserInfo/Wallet.vue')
            },
            {
              path: 'userinfo',
              component: () => import('../views/UserInfo/Info.vue')
            },
            {
              path: 'settings',
              component: () => import('../views/UserInfo/Settings.vue')
            }
          ]
        },
        {
          path: '/admin',
          name: 'admin',
          component: () => import('../views/Admin/Admin.vue'),
          children: [
            {
              path: 'index',
              name: 'adminindex',
              component: () => import('../views/Admin/com/Index.vue')
            },
            {
              path: 'userman',
              name: 'userman',
              component: () => import('../views/Admin/com/UserMan.vue')
            },
            {
              path: 'message',
              name: 'adminmsg',
              component: () => import('../views/Admin/com/Message.vue')
            },
            {
              path: 'orderman',
              name: 'orderman',
              component: () => import('../views/Admin/com/OrderMan.vue')
            },
            {
              path: 'adminSys',
              name: 'adminsys',
              component: () => import('../views/Admin/com/SysSetting.vue')
            },
            {
              path: 'statistics',
              name: 'statistics',
              component: () => import('../views/Admin/com/Statistics.vue')
            }
          ]
        },
        {
          path: '/pay',
          name: 'Pay',
          component: () => import('../views/UserInfo/PayForBalance.vue')
        },
        {
          path: '/map',
          name: 'GuiJiMap',
          component: () => import('../views/common/GuiJiMap.vue')
        },
        {
          path: '/test',
          name: 'UnitTest',
          component: () => import('../views/common/UnitTest.vue')
        },
        {
          path: '/loading',
          name: 'Loading',
          component: () => import('../views/common/LoadingPage.vue')
        },
        {
          path: '/:pathMatch(.*)*',
          redirect: '/'
        }
      ]

      // 递归处理路由，构建路由映射
      const mapRoutes = (routeList, parentPath = '') =>
      {
        routeList.forEach(route =>
        {
          if (route.name)
          {
            const fullPath = route.path.startsWith('/')
              ? route.path
              : `${parentPath}/${route.path}`
            this.routeMap.push({
              name: route.name,
              path: fullPath,
              label: this.routeDisplayNames[route.name] || route.name
            })
          }
          if (route.children)
          
            mapRoutes(route.children, route.path.startsWith('/') ? route.path : `${parentPath}/${route.path}`)
        })
      }

      mapRoutes(routes)
      console.log('Route map initialized:', this.routeMap)
    },

    // 模糊匹配路由
    querySearch(queryString, cb)
    {
      const results = queryString
        ? this.routeMap.filter(route =>
        {
          const label = route.label.toLowerCase()
          const query = queryString.toLowerCase()
          return label.includes(query)
        })
        : this.routeMap
      cb(results)
    },

    // 点击搜索结果跳转
    handleSelect(item)
    {
      this.$router.push(item.path)
      this.searchQuery = '' // 清空搜索框
    },

    handleOpen(key, keyPath)
    {
      console.log('Menu opened:', key, keyPath)
    },
    handleClose(key, keyPath)
    {
      console.log('Menu closed:', key, keyPath)
    }
  }
}
</script>

<style scoped>
.main {
  display: flex;
  width: 100%;
  height: 100vh;
  position: relative;
  margin: 0;
}

.sidebar {
  padding: 50px 0 50px 0;
  border-radius: 10px;
  position: fixed;
  top: 5vh;
  left: 20px;
  width: 63px;
  height: 90%;
  background-color: #ffffff;
  transition: width 0.3s ease;
  z-index: 9;
  user-select: none;
}

.sidebar-expanded {
  width: 200px;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  height: 100%;
}

.main-content {
  flex: 1;
  transition: margin-left 0.3s ease;
  z-index: 1;
  background-color: #eef1f9;
}

.main-content.sidebar-expanded {
  margin-left: 200px;
}

.toggle-button {
  margin-top: 6px;
  margin-left: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.hamburger-icon {
  width: 30px;
  height: 30px;
  fill: none;
  stroke: black;
  stroke-width: 2;
}

.bar1,
.bar2,
.bar3 {
  transition: all 0.3s ease;
}

.toggle-button[aria-expanded="true"] .bar1 {
  transform: translateY(-30px) translateX(38px) rotate(45deg);
}

.toggle-button[aria-expanded="true"] .bar2 {
  opacity: 0;
}

.toggle-button[aria-expanded="true"] .bar3 {
  transform: translateY(30px) translateX(-40px) rotate(-45deg);
}

@media (max-width: 768px) {
  .toggle-button {
    right: 0;
  }
}

#logo {
  height: 20px;
  margin-bottom: 20px;
  box-sizing: border-box;
  position: relative;
  left: 50%;
  top: 6px;
  transform: translate(-50%);
  -webkit-user-drag: none;
}

.left,
.right {
  display: flex;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #333333;
  user-select: none;
}

.weather {
  text-align: center;
  padding: 0 20px 0 20px;
  margin: 0 20px 0 70px;
  line-height: 40px;
  background-color: #fff;
  font-weight: 500;
  border-radius: 20px;
  user-select: none;
  box-shadow: 3px 3px 6px #3333333e;
}

.search {
  height: 30px;
  width: 200px;
  font-weight: 500;
  font-size: 16px;
  border: transparent solid 2px;
  border-radius: 20px;
  padding-left: 36px;
  background: url(@/assets/search.svg) no-repeat #fff;
  background-position: 10px center;
  background-size: 18px 18px;
  -webkit-user-drag: none;
  box-shadow: 2px 2px 4px #3333333e;
}

:deep(.el-autocomplete .el-input__wrapper) {
  height: 30px;
  width: 200px;
  font-weight: 500;
  font-size: 16px;
  border: transparent solid 2px;
  border-radius: 20px;
  padding-left: 36px;
  background: url(@/assets/search.svg) no-repeat #fff;
  background-position: 10px center;
  background-size: 18px 18px;
  box-shadow: 2px 2px 4px #3333333e;
}

:deep(.el-autocomplete .el-input__inner) {
  height: 30px;
  font-weight: 500;
  font-size: 16px;
  border: none;
}

:deep(.el-autocomplete .el-input__inner:hover),
:deep(.el-autocomplete .el-input__inner:focus) {
  outline: none;
  border: none;
}

:deep(.el-autocomplete .el-input__wrapper:hover),
:deep(.el-autocomplete .el-input__wrapper.is-focus) {
  outline: none;
  border: #425aef solid 2px;
  box-shadow: none;
}

:deep(.el-autocomplete-suggestion) {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-autocomplete-suggestion li) {
  padding: 8px 12px;
  font-size: 14px;
  color: #333;
}

:deep(.el-autocomplete-suggestion li:hover) {
  background-color: #f5f5f5;
}

.bell {
  background-color: #425aef;
  border-radius: 50%;
  border: 0;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  transition: transform 0.2s ease-in-out;
  margin-left: 20px;
}

.bell:hover {
  box-shadow: 2px 2px 4px #3333333e;
  cursor: pointer;
  animation: shake 1s ease-in-out infinite;
}

@keyframes shake {
  0%,
  100% {
    transform: rotate(0deg);
  }
  25% {
    transform: rotate(-10deg);
  }
  50% {
    transform: rotate(10deg);
  }
  75% {
    transform: rotate(-10deg);
  }
}

.msg {
  position: absolute;
  top: 50px;
  right: 60px;
  width: 300px;
  height: 380px;
  background-color: #fff;
  box-shadow: 0 0 10px 5px rgba(128, 128, 128, 0.3);
  border-radius: 12px;
  z-index: 10;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.layout {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.logout {
  margin-left: 10px;
  font-size: 14px;
  color: black;
  transition: color 0.3s ease, transform 0.3s ease;
}
</style>
